import React, { useRef } from 'react';
import { Button, DatePicker, Form, Icon, Input, Select, Tooltip, Typography } from 'antd';
import moment from 'moment';
import FileUpload from '@/components/Custom/FileUpload';
import FormContainer from '@/pages/Organization/EmployeeManage/components/EmployeeInfoSections/FormContainer';
import RecordButton from '@/pages/Recruitment/containers/RecordButton';
import PreviewModal from '@/pages/EntryManage/components/Preview/PreviewModal';
import { createDictionary } from '@/dictionary';
import { IMG_TYPE, OFFICE_TYPE, PDF_TYPE } from '@/containers/upload/constant';
import styles from '../index.less';

const { Text } = Typography;
const [careTypeList, getCareTypeText] = createDictionary('CARE_TYPE_DICT');
const [careWayList, getCareWayText] = createDictionary('CARE_WAY_DICT');

const formItemLayout = {
    wrapperCol: { span: 8 },
    labelCol: { span: 3 }
};
/**
 * 员工关怀
 */
const EmployeeCareForm = ({ formData, index, onSubmit, onCancel, hasEditAuth, careListLength }) => {
    const recordButtonRef = useRef();
    const previewModalRef = useRef();
    const formRef = useRef();

    // 禁用日期
    // const disabledDate = endValue => {
    //     const startValue = new Date(moment(new Date()).format('YYYY-MM-DD 00:00:00'));
    //     if (!endValue || !startValue) {
    //         return false;
    //     }
    //     return endValue.valueOf() <= startValue.valueOf();
    // };

    // 保存
    const handleSubmit = async (values, form) => {
        const recordInfo = await recordButtonRef?.current?.getRecordInfo();
        const submitData = {
            ...formData,
            ...values,
            resourceRelation: values.resourceRelation?.uploadResourceFile && [
                values.resourceRelation.uploadResourceFile
            ],
            startDate: moment(values.startDate || formData.startDate).format('YYYY-MM-DD HH:mm:ss'),
            mediaResourceUrl: recordInfo?.recordUrl || formData.mediaResourceUrl
        };
        if (onSubmit) {
            await onSubmit(submitData, form);
        }
    };

    // 取消编辑
    const handleCancel = () => {
        if (onCancel) {
            onCancel(formData, index);
        }
    };

    // 预览附件
    const handlePreview = file => {
        const fileType = file.originName
            .split('.')
            .pop()
            .toLowerCase();
        if (IMG_TYPE?.includes(fileType)) {
            previewModalRef.current.open({
                type: 'image',
                origin: file.url
            });
        } else if (PDF_TYPE?.includes(fileType)) {
            previewModalRef.current.open({
                type: 'pdf',
                title: file.keyName,
                origin: file.url
            });
        } else if (OFFICE_TYPE?.includes(fileType)) {
            previewModalRef.current.open({
                type: 'office',
                title: file.keyName,
                origin: file.url,
                encode: true
            });
        }
    };

    // 渲染控制栏
    const renderCustomControls = ({
        editStatus,
        loading,
        handleSubmit: _handleSubmit,
        handleCancel: _handleCancel
    }) => {
        if (editStatus) {
            return (
                <div className={styles.firstCareControl}>
                    <Button type="primary" onClick={_handleSubmit} loading={loading}>
                        提交
                    </Button>
                    &emsp;
                    <Button onClick={_handleCancel}>取消</Button>
                    &emsp;
                </div>
            );
        }
        return null;
    };

    // render
    return (
        <>
            <FormContainer
                ref={formRef}
                title={`关怀${careListLength - index}${
                    formData.careType ? ` (${getCareTypeText(formData.careType)})` : ''
                }`}
                hasEditAuth={hasEditAuth}
                onSubmit={(values, form) => handleSubmit(values, form, index)}
                onCancel={() => handleCancel(formData, index)}
                defaultEdit={!formData.id}
                customControls={careListLength === 1 && !formData.id ? renderCustomControls : null}
                formItemLayout={formItemLayout}
            >
                {({ getFieldDecorator }, editStatus) => (
                    <>
                        {editStatus && (
                            <Form.Item label="关怀类型">
                                {getFieldDecorator('careType', {
                                    initialValue: formData?.careType,
                                    rules: [
                                        {
                                            required: true,
                                            message: '关怀类型不能为空'
                                        }
                                    ]
                                })(
                                    <Select placeholder="请选择关怀类型">
                                        {careTypeList?.map(item => (
                                            <Select.Option value={item.value} key={item.value}>
                                                {item.text}
                                            </Select.Option>
                                        ))}
                                    </Select>
                                )}
                            </Form.Item>
                        )}
                        <Form.Item label="关怀发起人">
                            {editStatus ? (
                                <Input value={formData.careStarterName} disabled />
                            ) : (
                                <Text>{formData.careStarterName}</Text>
                            )}
                        </Form.Item>
                        <Form.Item label="关怀时间">
                            {editStatus ? (
                                getFieldDecorator('startDate', {
                                    initialValue:
                                        formData?.startDate !== '' && formData?.startDate
                                            ? moment(formData?.startDate)
                                            : moment(new Date()),
                                    rules: [
                                        {
                                            required: true,
                                            message: '关怀时间不能为空'
                                        }
                                    ]
                                })(
                                    <DatePicker
                                        showTime
                                        format="YYYY-MM-DD HH:mm"
                                        // disabledDate={disabledDate}
                                        disabled={!!formData?.id}
                                        style={{ width: '100%' }}
                                        getCalendarContainer={trigger => trigger.parentElement}
                                    />
                                )
                            ) : (
                                <Text>
                                    {formData?.startDate && moment(formData?.startDate).format('YYYY-MM-DD HH:mm')}
                                </Text>
                            )}
                        </Form.Item>
                        <Form.Item label="关怀方式">
                            {editStatus ? (
                                getFieldDecorator('type', {
                                    initialValue: formData?.type,
                                    rules: [
                                        {
                                            required: true,
                                            message: '关怀方式不能为空'
                                        }
                                    ]
                                })(
                                    <Select
                                        placeholder="请选择关怀方式"
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                    >
                                        {careWayList?.map(item => (
                                            <Select.Option value={item.value} key={item.value}>
                                                {item.text}
                                            </Select.Option>
                                        ))}
                                    </Select>
                                )
                            ) : (
                                <Text>{formData?.type ? getCareWayText(formData?.type) : ''}</Text>
                            )}
                        </Form.Item>
                        <Form.Item label="录音">
                            {formData?.mediaResourceUrl && (
                                <audio
                                    src={formData?.mediaResourceUrl}
                                    controls="controls"
                                    style={{ display: 'block', height: '30px', width: '240px', marginTop: '5px' }}
                                >
                                    <track kind="captions" />
                                </audio>
                            )}
                            {editStatus && !formData?.mediaResourceUrl && (
                                <div style={{ marginTop: '2px', width: '115px' }}>
                                    <RecordButton cRef={recordButtonRef} />
                                </div>
                            )}
                        </Form.Item>
                        <Form.Item label="关怀纪要">
                            {editStatus ? (
                                getFieldDecorator('remark', {
                                    initialValue: formData?.remark ?? undefined
                                })(
                                    <Input.TextArea
                                        minLength={1}
                                        maxLength={50}
                                        rows={3}
                                        placeholder="请输入关怀纪要"
                                    />
                                )
                            ) : (
                                <Text>{formData.remark}</Text>
                            )}
                        </Form.Item>
                        <Form.Item label="相关资料">
                            {editStatus ? (
                                <>
                                    {getFieldDecorator('resourceRelation', {
                                        initialValue: {
                                            allFileList:
                                                formData?.employeeCareList?.map(item => ({
                                                    ...item,
                                                    uid: item.keyName,
                                                    name: item.originName
                                                })) || []
                                        }
                                    })(
                                        <FileUpload
                                            checkFileSize={10}
                                            checkFileSizeMsg="文件大小不能超过10MB！"
                                            checkFileType="JPG,JPEG,PNG,PDF"
                                            checkFileTypeMsg="只能上传JPG,JPEG,PNG,PDF格式的文件！"
                                            categoryCode="employeeCareList"
                                        >
                                            <Button type="primary" ghost>
                                                <Icon type="upload" />
                                                上传文件
                                            </Button>
                                        </FileUpload>
                                    )}
                                    <div style={{ color: '#999', lineHeight: '1.5em' }}>
                                        支持png、jpg、pdf上传，大小为10M以内的文件。
                                    </div>
                                </>
                            ) : (
                                <div className={styles.filesWrapper}>
                                    {formData?.employeeCareList?.map(file => (
                                        <div key={file.keyName} className="file">
                                            <Tooltip placement="top" title={file.keyName}>
                                                <span className="fileName">{file.originName}</span>
                                            </Tooltip>
                                            {['pdf', 'jpg', 'jpeg', 'png'].includes(
                                                file.originName.split('.').pop()
                                            ) && (
                                                <span className="control">
                                                    <a onClick={() => handlePreview(file)}>
                                                        <Icon type="eye" />
                                                    </a>
                                                </span>
                                            )}
                                            <span className="control">
                                                <a href={file.url}>
                                                    <Icon type="download" />
                                                </a>
                                            </span>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </Form.Item>
                    </>
                )}
            </FormContainer>
            <PreviewModal height="650px" ref={previewModalRef} />
        </>
    );
};

export default EmployeeCareForm;
